﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Spacer {
	public class Pawn : Entity {
		public Pawn() {
			Inventory = new List<Item>();
		}

		public Pawn( SolarSys world ) : base(world) {
			if( this.GetType() == typeof(Pawn) ) Initialize();
			Inventory = new List<Item>();
		}

		// ----------

		public override bool CreateSaveState( EntitySaveState save ) {
			base.CreateSaveState( save );

			List<EntitySaveState> inv = new List<EntitySaveState>();
			save["InventoryStates"] = inv;

			foreach(Item i in Inventory) {
				EntitySaveState state = new EntitySaveState( i );
				state.EntityID = Guid.Empty;

				inv.Add( state );
			}

			return true;
		}

		public override void PostLoad() {
			base.PostLoad();

			List<EntitySaveState> inv = (List<EntitySaveState>)LoadedSaveState["InventoryStates"];
			foreach(EntitySaveState item_state in inv) {
				((Item)Entity.CreateFromSaveState(item_state,World,false)).GiveTo( this );
			}
		}

		// ----------

		public override void OnDeath( Entity instigator, Entity inflictor ) {
			foreach(Item item in Inventory) {
				item.OnOwnerDeath( instigator, inflictor );
			}
			Inventory.Clear();
		}

		// ----------
		
		public virtual Vector2 GetShootPos() {
			if( PhysicsObject != null ) {
				Vector2 offset = Vector2.Transform( PhysicsObject.LocalCenter, Matrix.CreateRotationZ(Angle) );
				return Position + offset;
			}

			return Position;
		}

        public virtual Vector2 GetShootPos( Vector2 amount ) {
            if( PhysicsObject != null ) {
                Vector2 offset = Vector2.Transform( PhysicsObject.LocalCenter + amount, Matrix.CreateRotationZ(Angle) );
                return Position + offset;
            }

            return Position;
        }

		public Projectile FireProjectile( Type type, Vector2 pos ) {
			Projectile proj = (Projectile)Activator.CreateInstance( type, World );
            proj.Owner = this;
            proj.Position = pos;
            proj.Velocity = Velocity + new Vector2( (float)Math.Cos(Angle), (float)Math.Sin(Angle) ) * proj.Speed;
			return proj;
		}

		public T FindInventoryItem<T>() where T : Item { return (T)FindInventoryItem( typeof(T) ); }
		public Item FindInventoryItem( Type type ) {
			foreach(Item item in Inventory) {
				if( item.GetType() == type )
					return item;
			}
			return null;
		}

		// ----------

		public PlayerController ControllingPlayer { get; set; }

		public List<Item> Inventory { get; private set; }
		
		public int ActiveItemIndex { get; set; }
		
		public Item ActiveItem {
			get { return Inventory[ActiveItemIndex]; }
		}
	}
}
